import { customAlphabet } from 'nanoid';

export const getNanoid = (len = 10) => {
  // 定义一个只包含字母和数字的字符集
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  // 使用自定义字符集生成长度为 默认10位 的 ID
  const nanoidWithCustomAlphabet = customAlphabet(alphabet, len);
  return nanoidWithCustomAlphabet();
}

export const getAllBreadcrumbList = (menuList, parent = [], result = {}) => {
  for (const item of menuList) {
    result[item.path] = [...parent, item];
    if (item.children) getAllBreadcrumbList(item.children, result[item.path], result);
  }
  return result;
};

export function getShowMenuList(menuList, prefix = '') {
  const newMenuList = JSON.parse(JSON.stringify(menuList));
  return newMenuList.map(item => {
    const updatedItem = { ...item };
    updatedItem.path = prefix + item.path;
    if (item.children && item.children.length > 0) {
      updatedItem.children = getShowMenuList(item.children, updatedItem.path + '/');
    }
    return updatedItem;
  });
}

export function getFlatMenuList(menuList, prefix = '') {
  let newMenuList = (menuList && JSON.parse(JSON.stringify(menuList))) ?? [];
  return newMenuList.flatMap(item => {
    item.path = prefix + '/' + item.path
    return [item, ...(item.children ? getFlatMenuList(item.children, item.path) : [])]
  });
}

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    //throw new Error('error arguments', 'deepClone')
    return {}
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}


export function getParams(form) {
  const params = new URLSearchParams() // 创建对象
  for (var key in form) {
    params.append(key, form[key]) // 封装对象
  }
  return params
}

// 获取节点
export function findNodeInTree(treeList, id) {
  if (!treeList || !treeList.length) {
    return null;
  }
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].id === id) {
      return treeList[i]; // 找到目标节点并返回
    }
    const foundNode = findNodeInTree(treeList[i].children, id); // 递归查找子节点
    if (foundNode) {
      return foundNode; // 如果在子节点中找到则返回
    }
  }
  return null; // 如果未找到则返回 null
}
//添加节点
export function appendNodeInTree(id, tree, obj) {
  tree.forEach(ele => {
    if (ele.id === id) {
      ele.children ? ele.children.push(obj) : ele.children = [obj]
    } else {
      if (ele.children) {
        appendNodeInTree(id, ele.children, obj)
      }
    }
  })
  return tree
}
//修改节点
export function updateNodeInTree(treeList, id, obj) {
  if (!treeList || !treeList.length) {
    return;
  }
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].id == id) {
      treeList[i] = obj;
      break;
    }
    updateNodeInTree(treeList[i].children, id, obj);
  }
}
//删除节点
export function removeNodeInTree(treeList, id) { // 通过id从数组（树结构）中移除元素
  if (!treeList || !treeList.length) {
    return
  }
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].id === id) {
      treeList.splice(i, 1);
      break;
    }
    removeNodeInTree(treeList[i].children, id)
  }
}
//树形结构，root
export function treeToArray(treeObj, rootid) {
  const temp = []; // 设置临时数组，用来存放队列
  const out = []; // 设置输出数组，用来存放要输出的一维数组
  temp.push(treeObj);
  // 首先把根元素存放入out中
  let pid = rootid;
  const obj = deepClone(treeObj);
  obj.pid = pid;
  delete obj['children'];
  out.push(obj)
  // 对树对象进行广度优先的遍历
  while (temp.length > 0) {
    const first = temp.shift();
    const children = first.children;
    if (children && children.length > 0) {
      pid = first.id;
      const len = first.children.length;
      for (let i = 0; i < len; i++) {
        temp.push(children[i]);
        const obj = deepClone(children[i]);
        obj.pid = pid;
        delete obj['children'];
        out.push(obj)
      }
    }
  }
  return out
}
//生成唯一标志id
export function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 32; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23];
  var uuid = s.join("");
  return uuid;
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}